/*
 * @lc app=leetcode.cn id=599 lang=javascript
 *
 * [599] 两个列表的最小索引总和
 */

// @lc code=start
/**
 * @param {string[]} list1
 * @param {string[]} list2
 * @return {string[]}
 */
var findRestaurant = function(list1, list2) {
    if (list1.length < list2.length) {
        // 确保 list1 是长的那一个
        let temp = list1
        list1 = list2
        list2 = temp
    }
    let res = []
    let min = Infinity
    let map = new Map()
    for (let index = 1; index < list1.length + 1; index++) {
        const e1 = list1[index - 1];
        const e2 = list2[index - 1];
        let value1 = map.get(e1) || 0
        let value2 = map.get(e2) || 0
        if (e1 === e2 && 2 * index < min) {
            res = [e1]
            min = 2 * index
        } else if (e1 === e2 && 2 * index === min) {
            res.push(e1)
        }
        if (value1 || value2) {
            if (value1) {
                if (value1 + index < min) {
                    res = [e1]
                    min = value1 + index
                } else if (value1 + index === min) {
                    res.push(e1)
                }
            }

            if (value2) {
                if (value2 + index < min) {
                    res = [e2]
                    min = value2 + index
                } else if (value2 + index === min) {
                    res.push(e2)
                }
            }
        } else {
            if (e1) {
                map.set(e1, index)
            }
            if (e2) {
                map.set(e2, index)
            }
        }
    }
    console.log(map, min, res)
    return res
};
// @lc code=end


/* 

    一点都不优雅，做的有问题

*/

